package net.csdn.business.auth.component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.request.oauth.NewOauthCodeDTO;
import net.csdn.business.common.domain.vo.oauth.OauthCodeVO;
import net.csdn.business.common.oauth2.service.IOauthCodeService;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.common.util.SerializationUtils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;

@Slf4j
@RequiredArgsConstructor
public class CustomAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {

    private final IOauthCodeService oauthCodeService;

    private RandomValueStringGenerator generator = new RandomValueStringGenerator(64);

    @Override
    public String createAuthorizationCode(OAuth2Authentication authentication) {
        String code = this.generator.generate();
        this.store(code, authentication);
        return code;
    }

    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        byte[] authByte= SerializationUtils.serialize(authentication);
        NewOauthCodeDTO newOauthCode=new NewOauthCodeDTO();
        newOauthCode.setCode(code);
        newOauthCode.setAuthentication(authByte);
        oauthCodeService.insertOauthCode(newOauthCode);
    }

    @Override
    protected OAuth2Authentication remove(String code) {
        OAuth2Authentication authentication=null;
        try {
            //根据code删除authentication
            OauthCodeVO codeVO=oauthCodeService.selectOauthCodeByCode(code);
            if(codeVO!=null){
                authentication = (OAuth2Authentication) SerializationUtils.deserialize(codeVO.getAuthentication());
            }
        } catch (EmptyResultDataAccessException var4) {
            return null;
        }
        if (authentication != null) {
            //根据code删除authentication
            oauthCodeService.deleteOauthCodeByCode(code);
        }
        return authentication;
    }
}
